package com.huifaapp.mall.base.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huifaapp.mall.R;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.base.bean.BaseBean;
import com.huifaapp.mall.base.bean.BaseListDataBean;
import com.huifaapp.mall.bean.BaseBeans;
import com.huifaapp.mall.view.DividerLine;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import java.util.List;

import io.reactivex.Observable;


/**
 * @author: wangZ
 * @date：2017/4/12 14:35
 * FileName：BaseRefreshFragment
 * @description： 到刷新功能Fragment
 */

public abstract class BaseRefreshFragment<T> extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener, SpringView.OnFreshListener {
    /**
     * 普通list布局
     */
    public static final int LINEAR_LAYOUT_MANAGER = 0;
    /**
     * grid布局
     */
    public static final int GRID_LAYOUT_MANAGER = 1;
    /**
     * 瀑布流布局
     */
    public static final int STAGGERED_GRID_LAYOUT_MANAGER = 2;
    /**
     * 默认为list布局
     */
    private int mListType = LINEAR_LAYOUT_MANAGER;
    /**
     * 排列方式默认垂直
     */
    private boolean mIsVertical = true;
    /**
     * grid布局与瀑布流布局默认行数
     */
    private int mSpanCount = 1;

    protected RecyclerView recyclerView;
    protected SpringView springView;
    private mYlistAdapter mAdapter;
    private View notDataView;
    private View errorView;
    protected boolean isPull;//记录 上啦加载的操作
    protected boolean mHasMore = true;  //记录是否还有更多数据
    /**
     * 页数(起始页数根据需求而定)
     */
    protected int page = 1;
    //默认分割线
    private DividerLine defaultDividerLine;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view, savedInstanceState);
    }

    /**
     * 设置View
     *
     * @param view
     * @param savedInstanceState
     */
    protected void initView(View view, Bundle savedInstanceState) {
        recyclerView = (RecyclerView) view.findViewById(R.id.base_recycler_view);
        springView = (SpringView) view.findViewById(R.id.base_spring_view);
//        recyclerView.setHasFixedSize(true); //固定大小
        intRecyclerView();
        initSpringView();
        requestFirst();
    }

    protected void initSpringView() {
        springView.setType(SpringView.Type.FOLLOW);  //设置跟随
        springView.setType(SpringView.Type.FOLLOW);  //设置跟随
        //齿轮
        springView.setHeader(new DefaultHeader(getActivity()));//头
        springView.setListener(this);

    }

    /**
     * 初始化RecyclerView
     */
    protected void intRecyclerView() {
        if (0 == getItemLayout()) {
            throw new RuntimeException("layoutResId is null!");
        }
        mAdapter = new mYlistAdapter(getItemLayout());
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        //设置布局管理器
        recyclerView.setLayoutManager(chooseListType(mListType, mIsVertical));

        //设置分割线
        defaultDividerLine = new DividerLine(DividerLine.VERTICAL);
        defaultDividerLine.setSize(1);
        defaultDividerLine.setColor(Color.parseColor("#EEEEEE"));
        recyclerView.addItemDecoration(defaultDividerLine);
//        打开或关闭加载
        mAdapter.setEnableLoadMore(false);
        // 当列表滑动到倒数第N个Item的时候(默认是1)回调onLoadMoreRequested方法
//        adapter.setAutoLoadMoreSize(1);
        //设置刷新监听
        mAdapter.setOnLoadMoreListener(this, recyclerView);
        mAdapter.openLoadAnimation();//在加载时打开动画
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OnItemClick(adapter, view, position);
            }
        });

        //没有数据时候的View
        notDataView = getActivity().getLayoutInflater().inflate(R.layout.layout_emptydata, (ViewGroup) recyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestFirst();
            }
        });
        //加载失败时候的View
        errorView = getActivity().getLayoutInflater().inflate(R.layout.layout_error, (ViewGroup) recyclerView.getParent(), false);
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestFirst();
            }
        });
        //设置Adapter
        recyclerView.setAdapter(mAdapter);

    }

    /**
     * @param listType 选择布局种类
     */
    private RecyclerView.LayoutManager chooseListType(int listType, boolean isVertical) {
        switch (listType) {
            case LINEAR_LAYOUT_MANAGER:
                //设置布局管理器
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());

                linearLayoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
                return linearLayoutManager;
            case GRID_LAYOUT_MANAGER:
                GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), mSpanCount);

                gridLayoutManager.setOrientation(isVertical ? GridLayoutManager.VERTICAL : GridLayoutManager.HORIZONTAL);
                return gridLayoutManager;
            case STAGGERED_GRID_LAYOUT_MANAGER:
                //设置布局管理器
                StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager
                        (mSpanCount, isVertical ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL);
                return staggeredGridLayoutManager;
            default:
                //设置布局管理器
                LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());

                layoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);

                return layoutManager;
        }
    }

    /**
     * item点击事件
     *
     * @param adapter
     * @param view
     * @param position
     */
    public void OnItemClick(BaseQuickAdapter adapter, View view, int position) {
    }

    /**
     * 设置分割线
     *
     * @param decoration
     */
    private void setItemDecoration(RecyclerView.ItemDecoration decoration) {
        if (null != decoration) {
            recyclerView.addItemDecoration(decoration);
        }
    }

    /**
     * 移除recyclerView默认分割线
     */
    public void removeDefaultDividerLine() {
        if (recyclerView != null) {
            recyclerView.removeItemDecoration(defaultDividerLine);
        }
    }

    /**
     * 请求数据的钩子方法
     */
    protected void requestData() {
        getReqObservale()
                .compose(ApiManager.<BaseListDataBean<T>>handlResult())
                .subscribe(new ObserverCallback<BaseListDataBean<T>>() {
                    @Override
                    protected void onSuccessful(BaseListDataBean<T> resp) {
                        if (resp != null) {
                            handleResp(resp);
                        } else {
                            mAdapter.setEmptyView(notDataView);
                        }
                    }
                    @Override
                    protected void onError(String code, String errMsg) {
                        mAdapter.setEmptyView(errorView);

                    }
                });
    }


    /**
     * 刷新失败
     */

    public void loadMoreFail() {
        if (mAdapter.getItemCount() <= 0) {
            mAdapter.setEmptyView(errorView);
        } else {
            mAdapter.loadMoreFail();
        }
    }




    private void requestFirst() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                isPull = false;
                requestData();
                springView.onFinishFreshAndLoad();

//
            }
        }, 100);
    }

    private void requestNext() {
        if (mHasMore) {
            page++;
            isPull = true;
            requestData();
        }
    }

    /**
     * 处理数据
     * @param resp
     */
    protected void handleResp(BaseListDataBean<T> resp) {
        //当前页数
        int inPage = resp.getPage();
        //总页数
        int total = resp.getTotal();
        if (inPage < total) {
            mHasMore = true;
        } else {
            mHasMore = false;
        }
        List<T> datas = resp.getRows();
        showDatas(datas);
    }

    protected void showDatas(List<T> datas) {
        if (isPull) {
            mAdapter.addData(datas);
            mAdapter.loadMoreComplete(); //刷新完成加载更多

        } else {
            if (datas != null && datas.size() > 0) {
                //清空并设置数据
                mAdapter.setNewData(datas);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.setEmptyView(notDataView);
            }
        }
        setLoadMoreEnd(mHasMore);
//
    }
    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        requestFirst();

    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMoreRequested() {
        requestNext();
    }

    @Override
    public void onLoadmore() {
    }

    /**
     * 刷新结束 没有更多数据
     */
    private void setLoadMoreEnd(Boolean isNet) {
        if (!isNet) {
            mAdapter.loadMoreEnd(false);//传false显示没有更多文字,传 true不显示
        }
    }

    public class mYlistAdapter extends BaseQuickAdapter<T, BaseViewHolder> {

        public mYlistAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, T t) {
            setHolder(baseViewHolder, t);
        }
    }

    /**
     * @param type       布局管理type
     * @param isVertical 是否是垂直的布局 ，true垂直布局，false横向布局
     */
    protected void setListType(int type, boolean isVertical) {
        mListType = type;
        mIsVertical = isVertical;
    }
    /**
     * 为grid样式和瀑布流设置横向或纵向数量
     *
     * @param spanCount 数量
     */
    protected void setSpanCount(int spanCount) {
        if (spanCount > 0)
            mSpanCount = spanCount;
    }
    /**
     * 获取 网络的请的观察者
     *
     * @return
     */
    protected abstract Observable<BaseBeans<BaseListDataBean<T>>> getReqObservale();

    /**
     * adapter内的数据处理
     *
     * @param holder BaseViewHolder
     * @param t      泛型T
     */
    protected abstract void setHolder(BaseViewHolder holder, T t);

    /**
     * 获取Item布局
     */
    protected abstract int getItemLayout();
}
